﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;

namespace Enterprise.Utilities
{
    public static class CryptoHelper
    {
        // Methods
        public static string Decrypt(string target, string key, bool useHashing)
        {
            byte[] bytes;
            byte[] buffer3;
            byte[] inputBuffer = Convert.FromBase64String(target);
            if (useHashing)
            {
                using (MD5CryptoServiceProvider provider = new MD5CryptoServiceProvider())
                {
                    bytes = provider.ComputeHash(Encoding.UTF8.GetBytes(key));
                }
            }
            else
            {
                bytes = Encoding.UTF8.GetBytes(key);
            }
            
            using (TripleDESCryptoServiceProvider provider2 = new TripleDESCryptoServiceProvider())
            {
                provider2.Key = bytes;
                provider2.Mode = CipherMode.ECB;
                provider2.Padding = PaddingMode.PKCS7;
                buffer3 = provider2.CreateDecryptor().TransformFinalBlock(inputBuffer, 0, inputBuffer.Length);
            }
            return Encoding.UTF8.GetString(buffer3);
        }

        public static string Encrypt(string target, string key, bool useHashing)
        {
            byte[] buffer2;
            byte[] buffer3;
            byte[] bytes = Encoding.UTF8.GetBytes(target);
            if (useHashing)
            {
                using (MD5CryptoServiceProvider provider = new MD5CryptoServiceProvider())
                {
                    buffer2 = provider.ComputeHash(Encoding.UTF8.GetBytes(key));
                }
            }
            else
            {
                buffer2 = Encoding.UTF8.GetBytes(key);    
            }
            
            using (TripleDESCryptoServiceProvider provider2 = new TripleDESCryptoServiceProvider())
            {
                provider2.Key = buffer2;
                provider2.Mode = CipherMode.ECB;
                provider2.Padding = PaddingMode.PKCS7;
                buffer3 = provider2.CreateEncryptor().TransformFinalBlock(bytes, 0, bytes.Length);
            }
            return Convert.ToBase64String(buffer3, 0, buffer3.Length);
        }

    }
}
